package com.app.service.impl;

import com.app.dao.OrdersDao;
import com.app.feign.PileOpenFeign;
import com.app.service.OrdersServer;
import com.app.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.Orders;
import com.common.entity.ResponseResult;
import com.common.entity.User;
import com.common.utils.FileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.web.main.entity.vo.PileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * @author 王鑫
 * @create 2020 -11 -24 11:58
 */
@Service
public class OrdersServerImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersServer {

    @Autowired
    OrdersDao ordersDao;

    //引入openFeign
    @Autowired
    PileOpenFeign pileOpenFeign;

    @Autowired
    UserService userService;

    /**
     * 生成订单的Order对象
     *
     * @param orders
     * @param userId
     * @param pileId
     * @return
     */
    @Transactional
    @Override
    public Orders createOrders(Orders orders, String userId, String pileId) {
        //System.out.println("feign:" + pileOpenFeign.getOne(pileId));
        //这里调用连表查询拼Orders对象openFen调用
        orders.setUserId(userId);
        orders.setPileId(pileId);
        return orders;
    }

    /**
     * 添加订单到(Redis)
     *
     * @param orders
     */
    @Transactional
    @Override
    public int addorders(Orders orders) {
        int insert = baseMapper.insert(orders);
        return insert;
    }


    /**
     * 通过id删除订单
     *
     * @param id
     */
    @Transactional
    @Override
    public void deleteOrderById(String id) {
        baseMapper.deleteById(id);
    }


    /**
     * 修改订单信息
     *
     * @param orders
     */
    @Transactional
    @Override
    public void updataOrder(Orders orders) {
        //修改的充电费
        Double a = orders.getOrdersPileRechargeMoney();
        //修改的服务费
        Double b = orders.getOrdersPileServeMoney();
        //修改的停车费
        Double c = orders.getOrdersPileParkMoney();
        //修改的支付方式
        Integer d = orders.getOrdersPilePayment();
        //修改的充电开始时间
        String startTime = orders.getOrdersStartTime();
        //修改的充电结束时间
        String endTime = orders.getOrdersEndTime();

        //先通过id查询出该订单
        Orders newOrders = baseMapper.selectById(orders.getOrdersId());
        //再修改订单
        if (a != null) {
            newOrders.setOrdersPileRechargeMoney(a);
        }
        if (b != null) {
            newOrders.setOrdersPileServeMoney(b);
        }
        if (c != null) {
            newOrders.setOrdersPileParkMoney(c);
        }
        if (d != null) {
            newOrders.setOrdersPilePayment(d);
        }
        if (startTime != null) {
            newOrders.setOrdersStartTime(startTime);
        }
        if (endTime != null) {
            newOrders.setOrdersEndTime(endTime);
        }
        //执行修改
        baseMapper.updateById(newOrders);
    }


    /**
     * 通过id查询订单
     *
     * @param id
     * @return
     */
    @Override
    public Orders selectOrderById(String id) {
        Orders orders = baseMapper.selectById(id);
        return orders;
    }

    /**
     * 查询所有订单
     *
     * @return
     */
    @Override
    public List<Orders> selectAllOrders() {
        List<Orders> ordersList = baseMapper.selectList(null);
        return ordersList;
    }


    /**
     * 分页查询所有订单
     *
     * @param page
     */
    @Override
    public void selectOrdersByPage(Page<Orders> page) {
        baseMapper.selectPage(page, null);
    }

    /**
     * 多条件分页查询订单
     *
     * @param page
     * @param orders
     */
    @Override
    public void selectOrdersByPageAndCondition(Page<Orders> page, Orders orders) {
        //订单用户id
        String userId = orders.getUserId();
        //订单电桩id
        String pileId = orders.getPileId();
        //充电费
        Double a = orders.getOrdersPileRechargeMoney();
        //服务费
        Double b = orders.getOrdersPileServeMoney();
        //停车费
        Double c = orders.getOrdersPileParkMoney();
        //支付方式
        Integer d = orders.getOrdersPilePayment();
        //充电开始时间
        String startTime = orders.getOrdersStartTime();
        //充电结束时间
        String endTime = orders.getOrdersEndTime();

        //构造查询条件
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            queryWrapper.like("user_id", userId);
        }
        if (!StringUtils.isEmpty(pileId)) {
            queryWrapper.like("pile_id", pileId);
        }
        if (!StringUtils.isEmpty(a)) {
            queryWrapper.eq("orders_pile_recharge_money", a);
        }
        if (!StringUtils.isEmpty(c)) {
            queryWrapper.eq("orders_pile_park_money", c);
        }
        if (!StringUtils.isEmpty(b)) {
            queryWrapper.eq("orders_pile_serve_money", b);
        }
        if (!StringUtils.isEmpty(d)) {
            queryWrapper.eq("orders_pile_payment", d);
        }
        if (startTime != null) {
            queryWrapper.ge("orders_start_time", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("orders_end_time", endTime);
        }
        //开启分页
        baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 通过UserId查询订单
     */
    @Override
    public List<Orders> selectOrderByUserId(String userId) {
        //构造查询条件
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Orders> ordersList = baseMapper.selectList(queryWrapper);
        return ordersList;
    }

    /**
     * @param orders
     * @param userPhone
     * @param pileId
     * @return 通过账号添加最终订单
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
    })
    @Transactional
    @Override
    public Orders generateOrders(Orders orders, String userPhone, String pileId) {
        //将电话号码转换为用户id
        String userId = userService.getUserId(userPhone);
        //通过用户id查用户对象
        User user = userService.getUserById(userId);
        //调用feign得出pileVo对象
        ResponseResult result = pileOpenFeign.getOne(pileId);
        Map<String, Object> data = (Map<String, Object>) result.getData();
        //将map封装转换为对象
        ObjectMapper objectMapper = new ObjectMapper();
        PileVo pileVo = objectMapper.convertValue(data.get("pile"), PileVo.class);
        //获取充电费（单价xx元/小时）
        Double supplierRechargeMoney = pileVo.getSupplierVo().getSupplierRechargeMoney();
        //获取服务费（单价xx元/小时）
        Double supplierServeMoney = pileVo.getSupplierVo().getSupplierServeMoney();
        //获取停车费（固定xx元）
        Double supplierParkMoney = pileVo.getSupplierVo().getSupplierParkMoney();
        //获取占用充电桩费用（单价xx元/分钟）
        Double supplierOccupyMonty = pileVo.getSupplierVo().getSupplierOccupyMonty();
        //获取充电开始时间String类型
        String ordersStartTime = orders.getOrdersStartTime();
        //获取充电结束时间String类型
        String ordersEndTime = orders.getOrdersEndTime();
        //获取占用充电桩结束时间
        String ordersOutTime = orders.getOrdersOutTime();
        //计算总费用
        Double file = null;
        try {
            file = new FileUtil().getOrdersFile(supplierRechargeMoney, supplierServeMoney, supplierParkMoney, supplierOccupyMonty, ordersOutTime, ordersStartTime, ordersEndTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //拼装Orders
        orders.setUser(user);
        orders.setPile(pileVo);
        orders.setUserId(userId);
        orders.setPileId(pileId);
        orders.setOrdersPileRechargeMoney(supplierRechargeMoney);
        orders.setOrdersPileServeMoney(supplierServeMoney);
        orders.setOrdersPileParkMoney(supplierParkMoney);
        orders.setOrdersPileOccupyMonty(supplierOccupyMonty);
        orders.setOrdersStartTime(ordersStartTime);
        orders.setOrdersEndTime(ordersEndTime);
        orders.setOrdersOutTime(ordersOutTime);
        orders.setOrdersBigDecimal(file);
        return orders;
    }


}
